//
//  StartWorkoutViewController.swift
//  BUYOU
//
//  Created by tyuu on 2024/6/1.
//

import UIKit
import CoreLocation


import UIKit
import CoreLocation
import SnapKit

class StartWorkoutViewController: UIViewController, CLLocationManagerDelegate {
    
    var workoutType: String
    var timer: Timer?
    var startTime: Date?
    var elapsedTime: TimeInterval = 0.0
    var locationManager: CLLocationManager!
    var currentSpeed: CLLocationSpeed = 0.0

    let timerLabel = UILabel()
    let speedLabel = UILabel()
    let startButton = UIButton(type: .system)
    let pauseButton = UIButton(type: .system)
    let endButton = UIButton(type: .system)

    init(workoutType: String) {
        self.workoutType = workoutType
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        setupViews()
        setupConstraints()
        updateTimerLabel()
        if workoutType == "自由跑" {
            updateSpeedLabel()
            
            // 初始化位置管理器
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
        }
       
    }
    
    // 设置视图
    private func setupViews() {
        timerLabel.font = UIFont.systemFont(ofSize: 32)
        timerLabel.textAlignment = .center
        
        speedLabel.font = UIFont.systemFont(ofSize: 24)
        speedLabel.textAlignment = .center
        speedLabel.textColor = .red
        
        startButton.setTitle("开始", for: .normal)
        startButton.setTitleColor(.white, for: .normal)
        startButton.backgroundColor = .blue
        startButton.layer.cornerRadius = 5
        startButton.clipsToBounds = true
        startButton.addTarget(self, action: #selector(startTapped), for: .touchUpInside)
        
        pauseButton.setTitle("暂停", for: .normal)
        pauseButton.setTitleColor(.white, for: .normal)
        pauseButton.backgroundColor = .orange
        pauseButton.layer.cornerRadius = 5
        pauseButton.clipsToBounds = true
        pauseButton.addTarget(self, action: #selector(pauseTapped), for: .touchUpInside)
        
        endButton.setTitle("结束", for: .normal)
        endButton.setTitleColor(.white, for: .normal)
        endButton.backgroundColor = .red
        endButton.layer.cornerRadius = 5
        endButton.clipsToBounds = true
        endButton.addTarget(self, action: #selector(endTapped), for: .touchUpInside)
        
        view.addSubview(timerLabel)
        view.addSubview(speedLabel)
        view.addSubview(startButton)
        view.addSubview(pauseButton)
        view.addSubview(endButton)
    }

    // 设置约束
    private func setupConstraints() {
        timerLabel.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide).offset(50)
            make.left.right.equalTo(view).inset(20)
        }
        
        speedLabel.snp.makeConstraints { make in
            make.top.equalTo(timerLabel.snp.bottom).offset(20)
            make.left.right.equalTo(view).inset(20)
        }
        
        startButton.snp.makeConstraints { make in
            make.top.equalTo(speedLabel.snp.bottom).offset(50)
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view.snp.centerX).offset(-10)
            make.height.equalTo(50)
        }
        
        pauseButton.snp.makeConstraints { make in
            make.top.equalTo(speedLabel.snp.bottom).offset(50)
            make.left.equalTo(view.snp.centerX).offset(10)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
        }
        
        endButton.snp.makeConstraints { make in
            make.top.equalTo(startButton.snp.bottom).offset(20)
            make.left.right.equalTo(view).inset(20)
            make.height.equalTo(50)
        }
    }
    
    // 更新计时器标签
    private func updateTimerLabel() {
        let minutes = Int(elapsedTime) / 60
        let seconds = Int(elapsedTime) % 60
        timerLabel.text = String(format: "%02d:%02d", minutes, seconds)
    }
    
    // 更新速度标签
    private func updateSpeedLabel() {
        speedLabel.text = String(format: "当前速度: %.2f m/s", currentSpeed)
    }
    
    // 开始按钮点击事件
    @objc private func startTapped() {
        if timer == nil {
            startTime = Date()
            timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
                self.elapsedTime = Date().timeIntervalSince(self.startTime!) + self.elapsedTime
                self.startTime = Date()
                self.updateTimerLabel()
            }
            
            if workoutType == "自由跑" {
                locationManager.startUpdatingLocation()
            }
        }
    }
    
    // 暂停按钮点击事件
    @objc private func pauseTapped() {
        timer?.invalidate()
        timer = nil
        if workoutType == "自由跑" {
            locationManager.stopUpdatingLocation()
        }
        
    }
    
    // 结束按钮点击事件
    @objc private func endTapped() {
        timer?.invalidate()
        timer = nil
        if workoutType == "自由跑" {
            locationManager.stopUpdatingLocation()
        }
        
        let alert = UIAlertController(title: "结束运动", message: "本次运动 \(workoutType) 共计时长 \(formatElapsedTime()) 分钟", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { _ in
            self.dismiss(animated: true, completion: nil)
        }))
        present(alert, animated: true, completion: nil)
    }
    
    // 格式化计时器显示
    private func formatElapsedTime() -> String {
        let minutes = Int(elapsedTime) / 60
        let seconds = Int(elapsedTime) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }

    // CLLocationManagerDelegate 方法
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        currentSpeed = location.speed
        updateSpeedLabel()
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Failed to get user location: \(error.localizedDescription)")
    }
}
